package core;

import branch.Branch;
import fileoperation.FileCreation;
import fileoperation.FileDeletion;
import fileoperation.FileReader;
import fileoperation.FileStatus;
import gitobject.Commit;
import repository.Repository;

import java.io.File;
import java.util.Date;


public class JitBranch {

    /*
    createBranch新建分支以后：
        1. .jit/logs/HEAD:
                内容： lastCommit.key   currentCommit.key  authorName email date "moving from {lastBranch} to {test} "
        2. .jit/logs/refs/heads/新增branchName :
                内容： lastCommit.key  currentCommit.key  authorName email date "moving from {lastBranch} to {test} "
        3. .jit/refs/heads/新增branchName
                内容： currentCommit.key
    */
    public static void createBranch(String branchName,Boolean flag) throws Exception {
        if(!new File(Branch.getRefsPath()+File.separator+"heads"+File.separator+"master").exists()){
            System.out.println("Master Branch Should Be Initialized Before Create A New Branch!");
            return;
        }
        String lastCommit = Commit.getLastCommit();
        // 如果分支存在的话，抛出错误
        if(FileStatus.branchExist(branchName)){
            System.out.println("The Branch Name Occupied!");
            return;
        }
        String saveInfo = lastCommit + " " + lastCommit + " " + System.getProperty("user.name") + " " + "<664941471@qq.com>" +" " + String.valueOf(new Date().getTime() )+" "+"Branch Create"  ;
        // .jit/refs/heads/新建文件branchName
        FileCreation.createFile(Branch.getRefsPath() +File.separator+"heads",branchName,lastCommit);
        // .jit/logs/refs/heads/新建文件branchName :
        FileCreation.createFile(Branch.getLogsPath() + File.separator + "refs" + File.separator + "heads" , branchName,saveInfo);

        System.out.println("Branch "+ branchName +" Create Successfully!");
        if(flag){
            checkout(branchName);
        }
    }

    // 基于logs/HEAD里的currentBranch信息，返回branchname
    public static String getCurrentBranchName() throws Exception{
        // 从HEAD里取出目前分支存储commit信息的地址
        File HEAD = new File(Repository.getGitDir()+File.separator+"HEAD");
        if(HEAD.exists()){
            return FileReader.readValue(HEAD).substring(16).trim();
        }else{
            System.out.println("There Is No Branch Before First Jit Commit！");
            return null;
        }
    }

    // 切换分支
    public static void checkout(String branchName) throws Exception{
        // 判断是否存在
        if(FileStatus.branchExist(branchName)){
            Branch branch = new Branch(Commit.getLastCommit(),branchName);
            File Head = new File(Repository.getGitDir()+File.separator+"logs"+File.separator+"Head");
            String updateInfo = FileReader.readValue(Head) + branch.getUpdateInfo() + " checkout: moving from " + getCurrentBranchName() + " to " + branchName;
            FileReader.writeValue(Head.getPath(),updateInfo);

            File HEAD = new File(Repository.getGitDir() + File.separator + "HEAD");
            // 删除HEAD的内容后重新写入
            FileDeletion.deleteContent(HEAD);
            FileReader.writeValue(HEAD.getPath(),"ref:"+" "+ "refs"+File.separator + "heads" +File.separator+branchName);
            System.out.println("Branch Switch to " + branchName + " !");
        }else{
            System.out.println("Branch "+ branchName +" Doesn't Exist!");
        }
    }

    // 删除分支
    public static void deleteBranch(String branch) throws Exception{
        if(FileStatus.branchExist(branch)){
            // 不可删除当前分支
            if(getCurrentBranchName().equals(branch)){
                System.out.println("Current Branch Can't be Deleted! ");
            }else{
                // 删除分支
                FileDeletion.deleteFile(Branch.getLogsPath() + File.separator + "refs" + File.separator + branch);
                FileDeletion.deleteFile(Branch.getRefsPath() + File.separator + "heads" + File.separator +branch);
            }
        }else{
            System.out.println("Branch "+ branch +" Doesn't Exist!");
        }
    }

    // jit branch -a  打印分支信息
    public static void printBranches() throws Exception {
        String currentBranch = getCurrentBranchName();
        File heads = new File(Branch.getRefsPath()+ File.separator + "heads");
        try{
            File[] fs = heads.listFiles();
            for (File f : fs) {
                if (f.getName().equals(currentBranch)) {
                    System.out.println("* " + currentBranch);
                } else {
                    System.out.println(f.getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
